import json
from datetime import datetime
import uuid
import os
import sys


def resource_path(relative_path):
    """ Get absolute path to a resource. """
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    else:
        return os.path.abspath(relative_path)


'''
data = {
    "name": "张三",
    "age": 25,
    "email": "zhangsan@example.com"
}
'''


# 保存运行记录，包括参数状态和时间
def saveRecord(data, status, path):
    path = resource_path(path)
    try:
        # 对文件路径进行处理
        keys = data.keys()
        for key in keys:
            if key != "dir" and data["dir"] in str(data[key]):
                data[key] = data[key].replace(data["dir"]+'\\', "")
        data["dir"] = os.path.normpath(data["dir"])
        # 添加id, status, dateTime属性
        data['id'] = str(uuid.uuid4())
        data['status'] = status
        data['dateTime'] = datetime.now().strftime("%Y:%m:%d %H:%M:%S")
        # 如果文件不存在，则创建一个空的JSON数组
        if not os.path.exists(path):
            with open(path, 'w') as f:
                json.dump([], f)
        # 读取文件
        with open(path, 'r', encoding='utf-8') as file:
            jsonData = json.load(file)
        # 保存到文件
        with open(path, 'w') as f:
            jsonData.insert(0, data)
            # total = len(jsonData)
            # if total > 300:  # 保留300条记录
            #     jsonData.pop()
            json.dump(jsonData, f)
            # print(f'历史记录共{len(jsonData)}条，最大保存300条记录。')
    except Exception as e:
        print(f"路径：{path}\n运行记录保存失败原因:", e)


# 获取运行记录
def getRecord(path):
    path = resource_path(path)
    if not os.path.exists(path):  # 没有运行记录
        return {
            'status': 'error',
            'msg': '暂无历史记录，请运行后重试！'
        }
    with open(path, 'r', encoding='utf-8') as file:
        jsonData = json.load(file)
        if len(jsonData) == 0:  # 没有运行记录
            return {
                'status': 'error',
                'msg': '暂无历史记录，请运行后重试！'
            }
        return {
            'status': 'success',
            'data': jsonData
        }


# 删除运行记录
def delRecord(path, ids):
    path = resource_path(path)
    try:
        with open(path, 'r', encoding='utf-8') as file:
            jsonData = json.load(file)
        for id in ids:
            for item in jsonData:
                if item['id'] == id:
                    jsonData.remove(item)
                    break
        with open(path, 'w') as f:
            json.dump(jsonData, f)
        return {
            'status': 'success',
            'data': jsonData,  # 返回当前的所有历史记录
            'msg': '删除成功！'
        }
    except Exception as e:
        print(f"路径：{path}\n删除记录失败原因:", e)
